package redis

import (
	"context"
	"fmt"
	"time"

	"rosesbff/internal/conf"

	"github.com/go-redis/redis"
)

type Redis struct {
	client *redis.Client
}

func NewRedis(c *conf.Bootstrap) (*Redis, error) {
	client := redis.NewClient(&redis.Options{
		Addr:         c.Data.Redis.Addr,
		Password:     c.Data.Redis.Password,
		DialTimeout:  10 * time.Second,
		ReadTimeout:  30 * time.Second,
		WriteTimeout: 30 * time.Second,
		PoolSize:     30,
		PoolTimeout:  30 * time.Second,
		MinIdleConns: 10,
		DB:           11,
	})
	// 初始化协程池
	d := &Redis{
		client: client,
	}
	return d, nil
}

func (s *Redis) Client() *redis.Client {
	return s.client
}

// todo 定时任务清除redis中过期的token

func (s *Redis) SetLoginToken(ctx context.Context, token string, userId int64, expiresAt int64) error {
	cmd := s.client.WithContext(ctx).HSet("user_login_token", token, expiresAt)
	if err := cmd.Err(); err != nil {
		return err
	}
	cmd = s.client.WithContext(ctx).HSet("user_login_user_id", fmt.Sprintf("%d", userId), token)
	if err := cmd.Err(); err != nil {
		return err
	}
	return nil
}

func (s *Redis) HasLoginToken(ctx context.Context, token string) (bool, error) {
	cmd := s.client.WithContext(ctx).HGet("user_login_token", token)
	if err := cmd.Err(); err != nil {
		return false, err
	}
	return cmd.Val() == token, nil
}
